<template>
  <div>
    <h2>各设备总量</h2>
    <div class="chart" id="oneChart">
        图表内容
    </div>
  </div>
</template>

<script>
import { inject, onMounted, reactive } from "vue";

export default {
  setup() {
    let $echarts = inject("echarts");
    let $http = inject("axios");
    let data = reactive({});
    let xdata = reactive([]);
    let ydata = reactive([]);
    let myChart = null; // 存储 ECharts 实例

    // 更新图表数据
    function updateChart() {
      if (!myChart) {
        // 如果 myChart 未初始化，则初始化它
        myChart = $echarts.init(document.getElementById("oneChart"));
      }
      // 设置图表的选项
      myChart.setOption({
        grid: {
          top: "1%",
          left: "1%",
          right: "6%",
          bottom: "10%",
          containLabel: true,
        },
        xAxis: {
          type: "value",
          axisLine: {
            lineStyle: {
              color: "#fff",
            },
          },
        },
        yAxis: {
          type: "category",
          data: xdata,
          axisLine: {
            lineStyle: {
              color: "#fff",
            },
          },
        },
        series: [{
          label: {
            show: true,
            position: 'right',
            valueAnimation: true,
          },
          type: "bar",
          data: ydata,
          itemStyle: {
            normal: {
              barBorderRadius: [0, 20, 20, 0],
              color: new $echarts.graphic.LinearGradient(0, 0, 1, 0, [{
                offset: 0,
                color: "#005eaa",
              }, {
                offset: 0.5,
                color: "#339ca8",
              }, {
                offset: 1,
                color: "#cda819",
              }])
            }
          }
        }],
      });
    }

    async function getState() {
      try {
        const response = await $http.get('/one/get-counts');
        data.chartData = response.data.chartData; // 确保赋值的是chartData数组
        // 更新数据
        xdata.splice(0, xdata.length, ...(data.chartData || []).map(v => v.title));
        ydata.splice(0, ydata.length, ...(data.chartData || []).map(v => v.num));
        // 更新图表
        updateChart();
      } catch (error) {
        console.error('Error fetching data:', error);
      }
    }

    onMounted(() => {
      getState(); // 直接调用getState函数获取数据
    });

    return {
      getState, data, xdata, ydata, updateChart
    };
  }
}
</script>

<style scoped>
.chart{
  height: 3rem;
}
h2{
  height: 0.2rem;
  color: #0b5ae2;
  line-height: 0.25rem;
  text-align: center;
  font-size: 0.2rem;
}
</style>